<template>
    <div class="box">
      <div class="top">
        <h1>添加商品</h1>
      </div>
      <div class="content">
        <el-form  :model="form" ref="formRef" label-width="100px">
          <!-- 商品名称 -->
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="form.name" style="width: 95%;"></el-input>
          </el-form-item>
  
          <!-- 商品分类 -->
          <el-form-item label="商品分类">
            <el-select 
              v-model="form.category" 
              :options="options"
              placeholder="请选择商品分类" 
              style="width: 240px"
            >
              <el-option 
                v-for="item in options.slice(0, 10)"
                :label="item.cateName" 
                :value="item.cateName" 
              />
            </el-select>
          </el-form-item>
  
          <!-- 商品价格 -->
          <el-form-item label="商品价格" >
            <el-input-number 
              v-model="form.price"
              :min="0" 
              
            ></el-input-number>
          </el-form-item>
  
          <!-- 商品图片 -->
          <div class="con">
            <p>商品图片：</p>
            <el-upload 
            :action="'/api/goods/goods_img_upload'" 
            list-type="picture-card"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            >
              <img v-if="form.imgUrl" :src="'/api/upload/imgs/goods_img/'+form.imgUrl" style="width: 150px; height: 150px;object-fit: cover;"/>
              <div v-else class="el-upload__text">
                <el-icon><Plus /></el-icon>
                <div class="el-upload__hint"></div>
            </div>
            </el-upload>
          </div>
  
          <!-- 商品描述 -->
          <el-form-item label="商品描述" prop="goodsDesc" style="margin-top: 20px;">
            <el-input 
              v-model="form.goodsDesc" 
              style="width: 95%" 
              :rows="2" 
              type="textarea" 
            />
          </el-form-item>
  
          <el-button type="primary" style="margin-left:120px;" @click="submitForm">添加商品</el-button>
        </el-form>
      </div>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { reactive, ref} from 'vue'
  import {goodsImg,goodsAdd,getCate} from '../api/goods'
  import { ElMessage } from 'element-plus'
  import {serverUrl} from '../utils/common'
  import { Plus } from '@element-plus/icons-vue'
  
  const form = reactive({
    name: '',
    category: '', // 商品分类
    price: 0,   // 商品价格
    imgUrl: '', // 商品图片
    goodsDesc: '' // 商品描述
  })

  const formRef = ref()
  const options = ref([]) 
// 获取商品分类选项
const fetchCategories = async () => {
    try {
      await getCate().then(res => {
       console.log(res);
        options.value = res.categories;
        console.log(options.value);
      }) 
    }
    catch (error) {
        console.error('获取分类失败:', error); 
    }
}

fetchCategories()
const handleUploadSuccess = (res) => {
    console.log('上传成功，返回数据:', res);
    if (res.code === 0) { // 假设返回码 0 表示成功
        form.imgUrl = res.imgUrl.replace('/upload/imgs/goods_img/', '');
        console.log('imgUrl 被更新为:', form.imgUrl);
        ElMessage.success('图片上传成功');
    } else {
        ElMessage.error('图片上传失败');
    }
}

// 上传前的校验
const beforeUpload = (file) => {
    const isImage = /^image\//.test(file.type);
    const isLt2M = file.size / 1024 / 1024 < 2;
    console.log('beforeUpload 函数执行，文件:', file);

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        console.log('文件类型不符合要求');
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!');
        console.log('文件大小超过限制');
    }
    return isImage && isLt2M;
}
  // 提交表单
  const submitForm = async () => {
    if (!form.imgUrl) {
        ElMessage.error('请上传商品图片');
        return;
    }
    console.log(form);
    // 这里可以添加表单验证和提交逻辑
    try {
        const { code, msg } = await goodsAdd(form);
        if (code === 0) {
            ElMessage.success(msg);
            if (formRef.value) {
                formRef.value.resetFields();
            }
            // 重置表单后，全部字段都应该重置为初始值
            form.name = '';
            form.category = '';
            form.price = 0;
            form.imgUrl = '';
            form.goodsDesc = '';
        } else {
            ElMessage.error(msg);
        }
    } catch (error) {
        ElMessage.error('提交表单时出错');
    }
}
  </script>

<style scoped>
.box {
    width: 98%;
    height: 100%;
    /* display: flex; */
    background-color: #fff;
    border-radius: 6px;

}

.top {
    width: 100%;
    height: 6%;
    font-size: 18px;
    /* font-weight: bold; */
    border-bottom: 1px solid #888787;
}

.top h1 {
    margin-left: 20px;
    line-height: 40px;
}

.content {
    margin-top: 20px;
    /* width: 100%; */
    /* height: 94%; */
    /* display: flex;  */
}

.con {
    width: 100%;
    /* height: 10%; */
    display: flex;
    /* flex-direction: column; */
    margin-top: 20px;
    margin-left: 32px;
    color: #484747;
    font-size: 14px;
}
</style>